﻿/*
 * Copyright (C) 2023 - 2024 lchfj.cn
 * 
 * This file is part of FastestHost.
 * 
 * FastestHost is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * FastestHost is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with FastestHost. If not, see <https://www.gnu.org/licenses/>.
 */

namespace Cn.Lchfj.FastestHost
{
    internal class RunLocal(RunSetting setting) : RunBase(setting)
    {
        protected override async Task<IReadOnlyList<string>> CreatHostListAsync()
        {
            var hostlist = new List<string>();
            if (Setting.Path is not { Count: > 0 })
                return hostlist;

            foreach (var item in Setting.Path)
            {
                string text;
                if (item.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || item.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    text = await ReadFromUrlAsync(item);
                }
                else
                {
                    text = await ReadFromFile(item);
                }

                if (!string.IsNullOrWhiteSpace(text))
                    hostlist.AddRange(text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
            }


            return hostlist;
        }

        private static async Task<string> ReadFromFile(string item)
        {
            try
            {
                if (File.Exists(item))
                    return await File.ReadAllTextAsync(item);
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        private HttpClient? HttpClient;
        private async Task<string> ReadFromUrlAsync(string url)
        {
            HttpClient ??= new HttpClient();

            try
            {
                return await HttpClient.GetStringAsync(url);
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}
